package com.taotao.portal.interceptor;

import com.taotao.pojo.User;
import com.taotao.portal.service.UserService;
import com.taotao.util.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * describe:
 *
 * @author hong.zheng
 * @date 2018/09/25
 */
public class OrderInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //取用户token
        String token = CookieUtils.getCookieValue(request, "TT_TOKEN");
        //判断是否为空
        if (StringUtils.isBlank(token)) {
            //如果为空就是未登录状态
            //跳转到登录页面
            response.sendRedirect(userService.getLoginUrl() + "?redirect=" + getBaseURL(request));
            return false;
        } else {
            //如果能取到token说明用户可能已经登录
            //从sso中取用户信息，判断用户是否登录
            User user = userService.getUserByToken(token);
            //判断用户是否过期
            if (user == null) {
                //跳转到登录页面
                response.sendRedirect(userService.getLoginUrl() + "?redirect=" + getBaseURL(request));
                return false;
            } else {
                //用户已经登录，把用户信息放到request中
                request.setAttribute("user", user);
            }

        }
        //放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }

    private String getBaseURL(HttpServletRequest request) {
        String url = request.getScheme()
                + "://"
                + request.getServerName()
                + ":"
                + request.getServerPort()
                + request.getContextPath()
                + request.getRequestURI();
        return url;
    }

}
